﻿@{
    ViewBag.Title = "Index";
Layout = "~/Views/Shared/_CommonLayout.cshtml";
}
<script type="text/javascript" src="~/Scripts/jquery-easyui/jquery.easyui.min.js"></script>
<link type="text/css" href="~/Scripts/jquery-easyui/themes/default/easyui.css" rel="stylesheet" />
<link type="text/css" href="~/Scripts/jquery-easyui/themes/icon.css" rel="stylesheet" />
<link type="text/css" href="~/Content/themes/project/loading.css" rel="stylesheet"/>
<script type="text/javascript" src="http://api.map.baidu.com/api?v=2.0&ak=XjOymLQ7XokpmPICKh0xlSyw"></script>

<div id="reportdiv"  style="height:530px;width:1100px;">
    <div id="waitingdiv">
        @Html.Partial("~/Views/MonitorCenter/Loading.cshtml")
    </div>
    <div id="mapdiv" style="height:250px;width:1100px;"></div>
    <div id="datadiv"  style="height:280px;width:1100px;">
        <table id="datatable" class="easyui-datagrid"
                fitcolumns="true"    
                rownumbers="true"
                singleSelect="true"
                striped="true"
                loadMsg=""
                pagination="true"
                pageSize="20"
                fit="true"
                data-options="onDblClickRow:OnDblClickRow">
            <thead>
                <tr>
                    <th field="mName">车牌号</th>
                    <th field="mSim">SIM卡号</th>
                    <th field="mDepart">单位名称</th>
                    <th field="mLastTime">最后上报时间</th>
                    <th field="mInterval">离线时长</th>
                    <th field="mAddr" width="5000">离线位置</th>
                </tr>
            </thead>
        </table>
    </div>
    <input type="button" value="导出excel" onclick="ExportExcel()"/>
    <form id="exportForm" name="exportForm" method="post">
        <input type="hidden" id="data" name="data"/>
    </form>
</div>
<script>
    var vehicleInfo = {};
    var vehicleNums = [];
    var offlinedata;
    var poikey;
    function GetVehicleInfo() {
        var treeObj = window.parent.$.fn.zTree.getZTreeObj("tree");
        var vehicles = treeObj.getCheckedNodes();
        $.each(vehicles, function (index) {
            if (vehicles[index].sim && vehicles[index].sim != null) {
                vehicleInfo[vehicles[index].id] = {
                    name: vehicles[index].name.split(",")[0],
                    sim: vehicles[index].sim,
                    depart: vehicles[index].getParentNode().name
                }
                vehicleNums.push(vehicles[index].id);
            }
        });
    }
    $(document).ready(function () {
        InitPager($("#datatable"));
        GetVehicleInfo();
        InitBaiduMap("武汉市", 14, "mapdiv");
        GetData();
    });
    //初始化分页控件
    function InitPager(dg) {
        var pager = dg.datagrid('getPager');
        pager.pagination({
            pageSize: 20,//每页显示的记录条数，默认为10  
            beforePageText: '第',//页数文本框前显示的汉字  
            afterPageText: '页，共{pages}页',
            displayMsg: '当前显示{from}到{to}条记录，共{total}条记录',
            layout: ["first", "prev", "sep", "manual", "sep", "next", "last"]
        });
    }

    /*查询数据*/
    function GetData() {
        $("#waitingdiv").show();
        $.ajax({
            type: "post",
            url: "/OfflineAnalysis/GetData",
            data: {
                "vehicleNums": vehicleNums
            },
            traditional: true,
            success: function (data) {
                if (data != "" && data != null && data.total != 0) {
                    var nowTime = GetCurrentTime();
                    for (var i = 0; i < data.rows.length; i++) {
                        var row = data.rows[i];
                        row.mName = vehicleInfo[row.mNum].name;
                        row.mDepart = vehicleInfo[row.mNum].depart;
                        row.mSim = vehicleInfo[row.mNum].sim;
                        if (row.mLastTime == null || row.mLastTime == "") {
                            row.mLastTime = "暂无车辆最近GPS信息"
                        }
                        else {
                            row.mInterval = CaculateTime(row.mLastTime, nowTime);
                        }
                    }
                    $("#datatable").datagrid("loadData", { total: 0, rows: [] });
                    $('#datatable').datagrid({ loadFilter: pagerFilter }).datagrid('loadData', data);
                    $('#datatable').datagrid("getPager").pagination('select', 1);
                    offlinedata = data.originalRows;
                    poikey = (new Date).getTime() + "";
                    ParseAddr(2);
                }
                else {
                    $("#datatable").datagrid("loadData", { total: 0, rows: [] });
                    if (data != null && data.total == 0) {
                        artDialogAlert("没有数据");
                    }
                    else {

                    }
                }
                $("#waitingdiv").hide();
            },
            error: function (XMLHttpRequest) {
                $("#waitingdiv").hide();
                artDialogAlert("加载错误，错误代码：" + XMLHttpRequest.status);
            }
        });
    }
    /*本地分页*/
    function pagerFilter(data) {
        if (typeof data.length == 'number' && typeof data.splice == 'function') {    // is array
            data = {
                total: data.length,
                rows: data
            }
        }
        var dg = $(this);
        var opts = dg.datagrid('options');
        var pager = dg.datagrid('getPager');
        pager.pagination({
            pageSize: 20,//每页显示的记录条数，默认为10  
            beforePageText: '第',//页数文本框前显示的汉字  
            afterPageText: '页，共{pages}页',
            displayMsg: '当前显示{from}到{to}条记录，共{total}条记录',
            layout: ["first", "prev", "sep", "manual", "sep", "next", "last"],
            onSelectPage: function (pageNum, pageSize) {
                opts.pageNumber = pageNum;
                opts.pageSize = pageSize;
                pager.pagination('refresh', {
                    pageNumber: pageNum,
                    pageSize: pageSize
                });
                dg.datagrid('loadData', data);
            }
        });
        if (!data.originalRows) {
            data.originalRows = (data.rows);
        }
        var start = (opts.pageNumber - 1) * parseInt(opts.pageSize);
        var end = start + parseInt(opts.pageSize);
        data.rows = (data.originalRows.slice(start, end));
        return data;
    }

    /*计算时间差*/
    function CaculateTime(beginTime, endTime) {
        if(beginTime == null || endTime == null || beginTime == "" || endTime == ""){
            return;
        }
        var tmp = CaculateTime2(beginTime, endTime)
        return CaculateTime3(tmp);
    }
    function CaculateTime2(beginTime, endTime) {
        beginTime = beginTime.replace(/\-/g, "/");
        endTime = endTime.replace(/\-/g, "/");
        var sTime = new Date(beginTime); //开始时间
        var eTime = new Date(endTime);  //结束时间
        var tmp = parseInt(eTime.getTime() - sTime.getTime());
        if (tmp < 0)
            return 0;
        return tmp;
    }
    function CaculateTime3(tmp) {
        var days = Math.floor(tmp / (24 * 3600 * 1000))
        //小时数
        var leave1 = tmp % (24 * 3600 * 1000)//计算天数后剩余的毫秒数
        var hours = Math.floor(leave1 / (3600 * 1000))
        //分钟数
        var leave2 = leave1 % (3600 * 1000)//计算小时数后剩余的毫秒数
        var minutes = Math.floor(leave2 / (60 * 1000))
        //计算相差秒数
        var leave3 = leave2 % (60 * 1000)      //计算分钟数后剩余的毫秒数
        var seconds = Math.round(leave3 / 1000)
        return days + "天" + hours + "时" + minutes + "分" + seconds + "秒";
    }
    /*获取当前时间*/
    function GetCurrentTime() {
        var now = new Date();
        var year = now.getFullYear();       //年
        var month = now.getMonth() + 1;     //月
        var day = now.getDate();            //日
        var hh = now.getHours();            //时
        var mm = now.getMinutes();          //分
        var ss = now.getSeconds();          //秒
        if (month < 10)
            month = "0" + month;
        if (day < 10)
            day = "0" + day;
        if (hh < 10)
            hh = "0" + hh;
        if (mm < 10)
            mm = '0' + mm;
        if (ss < 10)
            ss = '0' + ss;
        var nowTime = year + "-" + month + "-" + day + " " + hh + ":" + mm + ":" + ss;
        return nowTime;
    }

    //解析地理位置
    function ParseAddr(index) {
        var options = $('#datatable').datagrid('getPager').data("pagination").options;
        var total = options.total;
        var curPage = options.pageNumber;
        var pageSize = options.pageSize;
        var pages = Math.ceil(options.total / options.pageSize);
        if (index <= pages) {
            var sIndex = (index - 1) * pageSize;
            var lngs = [];
            var lats = [];
            var length = 0;
            if (index < pages) {
                length = pageSize;
            }
            else {
                length = total - sIndex;
            }
            for (var j = 0; j < length; j++) {
                lngs.push(offlinedata[sIndex + j].mLng);
                lats.push(offlinedata[sIndex + j].mLat);
            }
            $.ajax({
                type: "post",
                url: "/OfflineAnalysis/ParseAddr",
                data: {
                    "lngs": lngs,
                    "lats": lats,
                    "key": poikey,
                    "page": index
                },
                traditional: true,
                success: function (data) {
                    if (data != null) {
                        var retPage = data.page;
                        var retKey = data.key;
                        var retPois = data.pois;
                        if (retKey == poikey) {//校验正确
                            var retsIndex = (retPage - 1) * pageSize;
                            for (var j = 0; j < length; j++) {
                                offlinedata[retsIndex + j].mAddr = retPois[j];
                            }
                            if (retPage == options.pageNumber) {//当前页
                                $('#datatable').datagrid("getPager").pagination('select', retPage);//刷新当前页数据
                            }
                        }
                    }
                }
            });
            setTimeout(function () {
                ParseAddr(++index);
            }, 500);
        }
    }

    /*百度地图*/
    //初始百度地图
    function InitBaiduMap(city, zoom, div) {
        if (m_Map == null) {
            m_Map = new BMap.Map(div);               // 创建Map实例
        }
        m_Map.centerAndZoom(city, zoom);
        m_Map.addControl(new BMap.NavigationControl());   // 添加平移缩放控件  
        m_Map.addControl(new BMap.ScaleControl());        // 添加比例尺控件  
        m_Map.addControl(new BMap.OverviewMapControl());  //添加缩略地图控件  
        m_Map.addControl(new BMap.MapTypeControl());      //添加地图类型控件  
        m_Map.enableScrollWheelZoom();                    //启用滚轮放大缩小
        m_Map.addEventListener("dblclick", ZoomIn);
    }
    //放大地图一级
    function ZoomIn() {
        m_Map.zoomIn();
    }
    //增加标注点
    var m_Map;
    function AddMarker(info) {
        m_Map.clearOverlays();
        if (info.mLng == null || info.mLat == null || info.mLng == "" || info.mLat == "") {
            artDialogAlert("没有《" + info.mName + "》的最近GPS信息");
            return;
        }
        var point = new BMap.Point(info.mLng, info.mLat);
        var marker = new BMap.Marker(point);
        var label = new BMap.Label(info.mName);
        label.setOffset(new BMap.Size(-17, 25));
        label.setStyle({ color: "white", backgroundColor: "#007898", border: "none", textAlign: "center", width: "60px" });
        marker.setLabel(label);
        m_Map.addOverlay(marker);
        m_Map.panTo(point);
    }

    function OnDblClickRow(rowIndex, rowData) {
        AddMarker(rowData);
    }

    function ExportExcel() {
        if (offlinedata != null && offlinedata.length != 0) {
            $("#data").val(JSON.stringify(offlinedata));
            $("#exportForm").attr("action", "/OfflineAnalysis/ExportExcel");
            $("#exportForm").submit();
        }
    }
</script>
